package monitor

import (
	"os"
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks2/function/system"
	"gitee.com/tomatomeatman/golang-repository/bricks2/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/ginutil"
)

// @Controller 监控信息控制器
type MonitorController struct{}

/**
 * 初始化
 */
func init() {

	//-- 接口注册 --//
	go ginutil.ControllerRegister("/monitor/load", MonitorController{}.Load, ginutil.POST)
	go ginutil.ControllerRegister("/monitor/logs", MonitorController{}.Logs, ginutil.POST)
	go ginutil.ControllerRegister("/monitor/pollcode", MonitorController{}.CreatePollCode, ginutil.POST)
}

// #region @Api {title=读取系统硬件信息}
// @return {type=json explainType=MsgEntity<map> explain=返回对象}
// @RequestMapping {name=Load type=POST value=/monitor/load}
// #endregion
func (control MonitorController) Load(ctx ginutil.Context) interface{} {
	result := map[string]interface{}{}

	result["AppMemory"] = system.AppMemoryInfo()
	result["SystemDisk"] = system.GetDiskInfo()
	result["SystemMemory"] = system.GetMemInfo()
	result["CPU"] = system.GetCpuInfo()
	result["OS"] = system.GetOsInfo()

	return msgentity.Success(result, "获取系统信息成功")
}

// #region @Api {title=读取系统日志}
// @return {type=json explainType=MsgEntity<string> explain=返回对象}
// @RequestMapping {name=Load type=POST value=/monitor/logs}
// #endregion
func (control MonitorController) Logs(ctx ginutil.Context) interface{} {
	Type := ctx.Request.Header.Get("type")
	if strings.TrimSpace(Type) == "" {
		Type = "error"
	}

	f, err := os.ReadFile("./logs/" + strings.ToLower(Type) + ".log")
	if err != nil {
		return msgentity.Err(9003, "读取日志文件失败")
	}

	return msgentity.Success(string(f), "读取日志文件成功")
}

// #region @Api {title=取系统序列号}
// @return {type=json explainType=MsgEntity<string> explain=返回对象}
// @RequestMapping {name=CreatePollCode type=POST value=/monitor/pollcode}
// #endregion
func (control MonitorController) CreatePollCode(ctx ginutil.Context) interface{} {
	result := system.GetSystemSerial()

	return msgentity.Success(result, "获取系统序列号成功")
}
